<?php
/**
 * Class for saving sessions to the database
 *
 * @package adroit
 */
class AdroitDBSession {

    /**
     * @var Integer session lifetime length
     */
    public $life_time;

    /**
     * Constructor
     *
     * @return AdroitDBSession
     */
    public function AdroitDBSession() {
        $this->life_time = get_cfg_var('session.gc_maxlifetime');
		$this->life_time = $this->life_time == '' ? '1440' : $this->life_time;
        session_set_save_handler(
        Array( $this, 'open' ),
        Array( $this, 'close' ),
        Array( $this, 'read' ),
        Array( $this, 'write'),
        Array( $this, 'destroy'),
        Array( $this, 'gc' )
        );
    }

    /**
     * Called for opening session
     *
     * @param String $save_path
     * @param String $session_name
     */
    public function open($save_path, $session_name) {
        global $sess_save_path;
        $sess_save_path = $save_path;
        return true;
    }

    /**
     * Called for closing session
     *
     */
    public function close() {
        return true;
    }

    /**
     * Called for loading session data from db
     *
     * @param String $id
     * @return Array
     */
    public function read($id) {
        $data = '';
        $time = time();
        $newid = mysql_real_escape_string($id);
        $query = 'SELECT `session_data` FROM `sessions`
					WHERE `session_id` = \'' . $newid . '\' AND `expires` > \'' . $time . '\'';
        $results = AdroitDB::$dbase->fetchAssocArray($query);
        if(count($results) > 0) {
            $data = $results[0]['session_data'];
        }
        return $data;
    }

    /**
     * Called to save session back to db
     *
     * @param String $id
     * @param String $data Serialized session data
     * @return boolean
     */
    public function write($id, $data) {
        $time = time() + $this->life_time;
        $newId = mysql_real_escape_string($id);
        $newData = mysql_real_escape_string($data);
        $query = 'REPLACE `sessions`
					(`session_id`,`session_data`,`expires`) 
					VALUES(\'' . $newId . '\', \'' . $newData . '\', \'' . $time . '\')';
        AdroitDB::$dbase->query($query);
        return true;
    }

    /**
     * Called for deleting a session from the db
     *
     * @param String $id
     * @return boolean
     */
    public function destroy($id) {
        $newId = mysql_real_escape_string($id);
        $query = 'DELETE FROM `sessions` WHERE `session_id` = \'' . $newId . '\'';
        AdroitDB::$dbase->query($query);
        return true;
    }

    /**
     * Called upon session garbage collection
     *
     * @return boolean
     */
    public function gc() {
        $query = 'DELETE FROM `sessions` WHERE `expires` < UNIX_TIMESTAMP();';
        AdroitDB::$dbase->query($query);
        return true;
    }
}
?>